package com.dx.utils.impl;
import com.dx.config.RestTemplateConfig;
import com.dx.result.R;
import com.dx.utils.DynamicRequestService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

//@Service
@RequiredArgsConstructor
public class DynamicRequestServiceImpl implements DynamicRequestService {

    private final RestTemplate restTemplate;

    public ResponseEntity<String> sendDynamicRequest(String url, HttpMethod method, HashMap<String, String> headers, Map<String, String > params, Object body) {
        // 创建HttpHeaders对象并添加请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        if(headers!=null&&!headers.isEmpty()){
            headers.forEach(httpHeaders::add);
        }

        // 创建HttpEntity对象并设置请求头和请求体
        HttpEntity<Object> requestEntity;
        if (body != null) {
            requestEntity = new HttpEntity<>(body, httpHeaders);
        } else {
            requestEntity = new HttpEntity<>(httpHeaders);
        }

        // 构建完整的URL（如果需要）
        if (params != null && !params.isEmpty()) {
            StringBuilder sb = new StringBuilder(url);
            sb.append("?");
            params.forEach((key, value) -> sb.append(key).append("=").append(value).append("&"));
            url = sb.toString().substring(0, sb.length() - 1); // 去掉最后一个&
        }
        // 发送请求
        return restTemplate.exchange(url, method, requestEntity, String.class);
    }

//    public DynamicRequestService setRestTemplate(RestTemplate restTemplate) {
//        this.restTemplate = restTemplate;
//        return this;
//    }
}